package com.gxa.web_admin.controller.zls;

import com.gxa.common.vo.R2;
import com.gxa.modules.common_log.MyLog;
import com.gxa.modules.service.zls.LoginService;
import com.gxa.web_admin.common.ResponseMap;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: zls
 * Date: 2021/12/28 10:46:37
 * Description:
 * Version: V1.0
 */
@Controller
@RequestMapping("/sys")
public class LoginController {
    //互亿
    private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LoginService loginService;

    @PostMapping(value = "/test1")
    @ResponseBody
    public R2 test1(){
        return new R2<>(200,"成功", ResponseMap.map);
    }

    //用户退出
    @RequestMapping(value = "/logout")
    public String logout () {
        Subject lvSubject=SecurityUtils.getSubject();
        lvSubject.logout();
        return "redirect:/";
    }

    //用户注册
    @PostMapping(value = "/userRegister")
    @ResponseBody
    public R2 register (@RequestBody Map map) {
        System.out.println(map);
        return loginService.addOrRegister(map);
    }

    //用户登录
    @MyLog(value = "登录")
    @PostMapping(value = "/userLogin")
    @ResponseBody
    public R2 login (@RequestBody Map map) {
        Object check = map.get("jiaose");
        System.out.println(map);
        if(true == (Boolean) check){
            return loginService.customerLogin(map);
        }else{
            System.out.println("controller---");
            String user_phone = (String) map.get("user_phone");
            String user_password = (String) map.get("user_password");
            R2 r2 = new R2(200,"登录成功");
            List<Map> uslList = loginService.queryMenu();
            Map role = loginService.queryRole1(user_phone);
            if(role != null){
                if ("管理员".equals(role.get("role_name"))){
                    r2.setData(ResponseMap.map);
                    r2.setData2(role);
                }else{
                    List<Map> map1 = loginService.queryShopInfo(user_phone);
                    List list = new ArrayList();
                    list.add(role);
                    list.add(uslList);
                    r2.setData(map1);
                    r2.setData2(list);
                }
            }
            System.out.println(user_phone + "\t" +user_password);
            Subject subject = SecurityUtils.getSubject();
            System.out.println(subject.isAuthenticated());
            try {
                System.out.println(user_phone + "\t" +user_password);
                UsernamePasswordToken token = new UsernamePasswordToken(user_phone,user_password);
                subject.login(token);
                System.out.println("传回----");
                return r2;
            }catch (Exception e){
                return new R2(500,"登录失败");
            }
        }
    }

    //修改密码
    @PostMapping(value = "/updatePassword")
    @ResponseBody
    public R2 updatePassword (@RequestBody Map map) {
        return loginService.updatePassword(map);
    }

    //忘记密码
    @PostMapping(value = "/updatePasswordForget")
    @ResponseBody
    public R2 updatePasswordForget (@RequestBody Map map) {
        return loginService.updatePasswordForget(map);
    }


    //登录短信验证接口
    @PostMapping(value = "/sendMsg")
    @ResponseBody
    public R2 sendMsg (@RequestBody Map map) {
        //获取手机号
        String user_phone = (String) map.get("user_phone");
        //发送准备
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Url);
        client.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");
        int mobile_code = (int)((Math.random()*9+1)*100000);
        String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
        NameValuePair[] data = {//提交短信
                new NameValuePair("account", "C57106164"), //查看用户名是登录用户中心->验证码短信->产品总览->APIID
                new NameValuePair("password", "f997b9f6404d81da2a8a13a09a587bb3"),  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", user_phone),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String SubmitResult =method.getResponseBodyAsString();
            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();
            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");
            if("2".equals(code)){
                System.out.println("短信提交成功");
                String keyCode = user_phone + "login";
                loginService.saveMsgCode(keyCode,mobile_code);//暂存缓存
                Object c = redisTemplate.boundValueOps(keyCode).get();
                System.out.println((Integer) c);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new R2(200,"验证出现异常");
        }
        return new R2(200,"短信已发送");
    }

    //忘记短信验证接口
    @PostMapping(value = "/sendMsg2")
    @ResponseBody
    public R2 sendMsg2 (@RequestBody Map map) {
        //获取手机号
        String user_phone = (String) map.get("user_phone");
        //发送准备
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Url);
        client.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");
        int mobile_code = (int)((Math.random()*9+1)*100000);
        String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
        NameValuePair[] data = {//提交短信
                new NameValuePair("account", "C57106164"), //查看用户名是登录用户中心->验证码短信->产品总览->APIID
                new NameValuePair("password", "f997b9f6404d81da2a8a13a09a587bb3"),  //查看密码请登录用户中心->验证码短信->产品总览->APIKEY
                new NameValuePair("mobile", user_phone),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String SubmitResult =method.getResponseBodyAsString();
            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();
            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");
            if("2".equals(code)){
                System.out.println("短信提交成功");
                String keyCode = user_phone + "forget";
                loginService.saveMsgCode2(keyCode,mobile_code);//暂存缓存
                Object c = redisTemplate.boundValueOps(keyCode).get();
                System.out.println((Integer) c);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new R2(200,"验证出现异常");
        }
        return new R2(200,"短信已发送");
    }

}
